package com.qidian.buy.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qidian.buy.entity.Item;
import com.qidian.buy.entity.ItemDesc;
import com.qidian.buy.product.mapper.ItemDescMapper;
import com.qidian.buy.product.mapper.ItemMapper;
import com.qidian.buy.product.service.IItemService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qidian.buy.util.pojo.BuyResult;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author 戴着假发的程序员
 * @since 2023-05-18
 */
@Service
public class ItemServiceImpl extends ServiceImpl<ItemMapper, Item> implements IItemService {
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ItemDescMapper itemDescMapper;
    @Autowired
    private FreeMarkerConfig freeMarkerConfig;
    @Value("${itemDetailDir}")
    private String itemDetailDir;
    @Override
    public void genHtml(Item item, ItemDesc itemDesc) {
        // 处理item的Images
        // 处理图片
        String image = item.getImage();// 图片地址是使用”；“
        if(image != null && !"".equals(image)){
            item.setImages(Arrays.asList(image.split(";")));
        }else{
            item.setImages(new ArrayList<>());
        }
        // 将图片的第一个设置到image属性中
        item.setImage(item.getImages().size()>0?item.getImages().get(0):"");
        // freemarker的configuration
        Configuration configuration = freeMarkerConfig.getConfiguration();
        // 获取模版
        try {
            Template template = configuration.getTemplate("item.ftlh");
            // 准备数据
            Map map = new HashMap();
            map.put("item",item);
            map.put("itemDesc",itemDesc);
            // 准备输出流
            FileWriter writer = new FileWriter(itemDetailDir+item.getId()+".html");
            // 执行模板
            template.process(map,writer);
            // 关闭流
            writer.close();
        } catch (IOException | TemplateException e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public BuyResult<Item> queryByPage(int pageNum, int limit, String title) {
        // ------------------
        IPage<Item> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(limit);
        QueryWrapper<Item> wrapper = new QueryWrapper<>();
        // 构造条件
        wrapper.like(title!=null && !"".equals(title),"title",title);
        // 查询
        page = itemMapper.selectPage(page,wrapper);
        // ------------------
        BuyResult<Item> result = BuyResult.ok();
        result.setCode(0);
        result.setCount(page.getTotal());
        result.setData(page.getRecords());
        return result;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public BuyResult saveItem(Item item, ItemDesc itemDesc) {
        // 暂时 查询最大的商品id+1操作
        QueryWrapper<Item> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id");
        wrapper.last(" limit 1 ");
        Item lastItem = itemMapper.selectOne(wrapper);
        // 补全数据
        item.setId(lastItem.getId()+1);
        item.setCreated(new Date());
        item.setStatus((byte) 1);
        item.setUpdated(new Date());
        // 保存商品
        itemMapper.insert(item);
        // 补全itemDesc的数据
        itemDesc.setItemId(item.getId());
        itemDesc.setCreated(new Date());
        itemDesc.setUpdated(new Date());
        itemDescMapper.insert(itemDesc);

        return BuyResult.ok(item);
    }

    @Override
    public BuyResult queryById(Long id) {
        // 查询商品信息
        Item item = itemMapper.selectById(id);
        // 查询商品详情信息
        ItemDesc itemDesc = itemDescMapper.selectById(id);
        // 准备一个map存储两个数据
        Map map = new HashMap();
        map.put("item",item);
        map.put("itemDesc",itemDesc);
        return BuyResult.ok(map);
    }


}
